package org.example.my.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.my.Utility.JWTUtility;
import org.example.my.model.BlogInfo;
import org.example.my.model.Result;
import org.example.my.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/blog")
@Slf4j
public class BlogController {
    @Autowired
    BlogService blogService;

    @RequestMapping("/selectBlogList")
    public List<BlogInfo> selectBlogList() {
        log.info("获取博客列表");
        return blogService.selectBlogList();
    }

    //根据博客id查询博客
    @RequestMapping("/selectBlogById")
    public BlogInfo selectBlogById(Integer id) {
        log.info("根据博客id查询博客");
        BlogInfo blogInfo = blogService.selectBlogById(id);
        log.info("blogInfo11111111111111111:{}", blogInfo);
        return blogInfo;
    }

    @RequestMapping("/deleteBlogByBlogId")
    public Result deleteBlogByBlogId(@RequestParam("id") Integer blogId){
        log.info("j接收到id:{}", blogId);
        log.info("根据博客id删除博客");
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        if(blogService.updateBlog(blogInfo) == 1){
            return Result.success(1);
        }
        return Result.fail("删除失败");
    }
    @RequestMapping("/insertBlog")
    public Integer insertBlog(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
        log.info("插入博客");
        log.info("blogInfo:{}", blogInfo);
        blogInfo.setUserId(JWTUtility.getUserId(request.getHeader("token")));
        return blogService.insertBlog(blogInfo);
    }

    //根据博客id更新博客
    @RequestMapping("/updateBlog")
    public Integer updateBlog(@RequestParam("id") Integer id,@RequestBody BlogInfo blogInfo){
        log.info("更新博客");
        log.info("blogInfo:{}", blogInfo);
        blogInfo.setId(id);
        return blogService.updateBlog(blogInfo);
    }
    @RequestMapping("/selectBlogCount")
    public Integer selectBlogCountByUserId(HttpServletRequest request){
        log.info("获取用户文章数量");
        Integer userId = JWTUtility.getUserId(request.getHeader("token"));
        return blogService.selectBlogCount(userId);
    }

    @RequestMapping("/selectBlogCountByBlogId")
    public Integer selectBlogCountByBlogId(@RequestParam("id") Integer blogId){
        log.info("获取用户文章数量");
        return blogService.selectBlogCount(blogId);
    }

}
